package com.kly.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.springbootinit.annotation.AuthCheck;
import com.kly.springbootinit.common.BaseResponse;
import com.kly.springbootinit.common.DeleteRequest;
import com.kly.springbootinit.common.ErrorCode;
import com.kly.springbootinit.common.ResultUtils;
import com.kly.springbootinit.constant.UserConstant;
import com.kly.springbootinit.exception.BusinessException;
import com.kly.springbootinit.exception.ThrowUtils;
import com.kly.springbootinit.model.dto.Clazz.ClazzAddRequest;
import com.kly.springbootinit.model.dto.Clazz.ClazzEditRequest;
import com.kly.springbootinit.model.dto.Clazz.ClazzQueryRequest;
import com.kly.springbootinit.model.dto.Clazz.ClazzUpdateRequest;
import com.kly.springbootinit.model.entity.Clazz;
import com.kly.springbootinit.model.entity.User;
import com.kly.springbootinit.model.vo.ClazzVO;
import com.kly.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 班级接口
 *
 * @author <a href="https://github.com/likly">程序员鹿七</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/Clazz")
@Slf4j
public class ClazzController {

    @Resource
    private ClazzService ClazzService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建班级
     *
     * @param ClazzAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addClazz(@RequestBody ClazzAddRequest ClazzAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(ClazzAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Clazz Clazz = new Clazz();
        BeanUtils.copyProperties(ClazzAddRequest, Clazz);
        // 数据校验
        ClazzService.validClazz(Clazz, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        Clazz.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = ClazzService.save(Clazz);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newClazzId = Clazz.getId();
        return ResultUtils.success(newClazzId);
    }

    /**
     * 删除班级
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteClazz(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Clazz oldClazz = ClazzService.getById(id);
        ThrowUtils.throwIf(oldClazz == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldClazz.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = ClazzService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新班级（仅管理员可用）
     *
     * @param ClazzUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateClazz(@RequestBody ClazzUpdateRequest ClazzUpdateRequest) {
        if (ClazzUpdateRequest == null || ClazzUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Clazz Clazz = new Clazz();
        BeanUtils.copyProperties(ClazzUpdateRequest, Clazz);
        // 数据校验
        ClazzService.validClazz(Clazz, false);
        // 判断是否存在
        long id = ClazzUpdateRequest.getId();
        Clazz oldClazz = ClazzService.getById(id);
        ThrowUtils.throwIf(oldClazz == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = ClazzService.updateById(Clazz);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取班级（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ClazzVO> getClazzVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Clazz Clazz = ClazzService.getById(id);
        ThrowUtils.throwIf(Clazz == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(ClazzService.getClazzVO(Clazz, request));
    }

    /**
     * 分页获取班级列表（仅管理员可用）
     *
     * @param ClazzQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Clazz>> listClazzByPage(@RequestBody ClazzQueryRequest ClazzQueryRequest) {
        long current = ClazzQueryRequest.getCurrent();
        long size = ClazzQueryRequest.getPageSize();
        // 查询数据库
        Page<Clazz> ClazzPage = ClazzService.page(new Page<>(current, size),
                ClazzService.getQueryWrapper(ClazzQueryRequest));
        return ResultUtils.success(ClazzPage);
    }

    /**
     * 分页获取班级列表（封装类）
     *
     * @param ClazzQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ClazzVO>> listClazzVOByPage(@RequestBody ClazzQueryRequest ClazzQueryRequest,
                                                               HttpServletRequest request) {
        long current = ClazzQueryRequest.getCurrent();
        long size = ClazzQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Clazz> ClazzPage = ClazzService.page(new Page<>(current, size),
                ClazzService.getQueryWrapper(ClazzQueryRequest));
        // 获取封装类
        return ResultUtils.success(ClazzService.getClazzVOPage(ClazzPage, request));
    }

    /**
     * 分页获取当前登录用户创建的班级列表
     *
     * @param ClazzQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ClazzVO>> listMyClazzVOByPage(@RequestBody ClazzQueryRequest ClazzQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(ClazzQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        ClazzQueryRequest.setUserId(loginUser.getId());
        long current = ClazzQueryRequest.getCurrent();
        long size = ClazzQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Clazz> ClazzPage = ClazzService.page(new Page<>(current, size),
                ClazzService.getQueryWrapper(ClazzQueryRequest));
        // 获取封装类
        return ResultUtils.success(ClazzService.getClazzVOPage(ClazzPage, request));
    }

    /**
     * 编辑班级（给用户使用）
     *
     * @param ClazzEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editClazz(@RequestBody ClazzEditRequest ClazzEditRequest, HttpServletRequest request) {
        if (ClazzEditRequest == null || ClazzEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Clazz Clazz = new Clazz();
        BeanUtils.copyProperties(ClazzEditRequest, Clazz);
        // 数据校验
        ClazzService.validClazz(Clazz, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = ClazzEditRequest.getId();
        Clazz oldClazz = ClazzService.getById(id);
        ThrowUtils.throwIf(oldClazz == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldClazz.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = ClazzService.updateById(Clazz);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
